package api

import (
	"encoding/json"
	"fmt"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"
	"supershare/backend/services"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// CouponController 微信小程序优惠券接口
type CouponController struct {
	web.Controller
}

// GetMyCoupons 获取我的优惠券列表
func (c *CouponController) GetMyCoupons() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取状态参数，默认获取所有状态
	status, _ := c.GetInt8("status", -1)

	// 获取会员的优惠券列表
	issues, err := models.GetMemberCoupons(member.Id, status)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 转换为前端需要的格式
	var result []map[string]interface{}
	for _, issue := range issues {
		// 获取优惠券信息
		coupon, err := models.GetCouponById(issue.CouponId)
		if err != nil {
			continue
		}

		// 组装数据
		item := map[string]interface{}{
			"id":                 issue.Id,
			"coupon_id":          coupon.Id,
			"name":               coupon.Name,
			"type":               coupon.Type,
			"amount":             coupon.Value,      // 转换为元
			"min_consume":        coupon.MinConsume, // 转换为元
			"discount":           coupon.Discount,
			"duration":           coupon.Duration,
			"valid_from":         issue.ValidFrom,
			"valid_until":        issue.ValidUntil,
			"start_time":         coupon.StartTime,
			"end_time":           coupon.EndTime,
			"status":             issue.Status,
			"description":        coupon.Description,
			"code":               issue.Code,
			"points":             100, // 默认值
			"condition":          fmt.Sprintf("订单金额满%.2f元可用", coupon.MinConsume),
			"validDays":          coupon.ValidDays / 30, // 转换为月，如果不足一个月显示为1个月
			"available_weekdays": coupon.AvailableWeekdays,
			"available_times":    coupon.AvailableTimes,
			"applicable_type":    coupon.ApplicableType,
			"applicable_ids":     coupon.ApplicableIds,
		}

		result = append(result, item)
	}

	// 返回数据
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券成功",
		"data":    result,
	}
	c.ServeJSON()
}

// GetAvailableCoupons 获取可用的优惠券
func (c *CouponController) GetAvailableCoupons() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析订单金额参数
	amount, _ := c.GetFloat("amount", 0)

	// 获取会员未使用的优惠券
	issues, err := models.GetMemberCoupons(member.Id, 0) // 状态0表示未使用
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 筛选可用的优惠券
	var availableCoupons []map[string]interface{}
	now := time.Now().Unix()

	for _, issue := range issues {
		// 检查有效期
		if now < issue.ValidFrom || now > issue.ValidUntil {
			continue
		}

		coupon, err := models.GetCouponById(issue.CouponId)
		if err != nil {
			continue
		}

		// 检查最低消费
		if coupon.MinConsume > 0 && amount < coupon.MinConsume {
			continue
		}

		availableCoupons = append(availableCoupons, map[string]interface{}{
			"id":          issue.Id,
			"coupon_id":   coupon.Id,
			"name":        coupon.Name,
			"type":        coupon.Type,
			"value":       coupon.Value / 100,
			"min_consume": coupon.MinConsume / 100,
			"description": coupon.Description,
			"use_rules":   coupon.UseRules,
			"valid_until": issue.ValidUntil,
			"valid_from":  issue.ValidFrom,
			"start_time":  coupon.StartTime,
			"end_time":    coupon.EndTime,
			"code":        issue.Code,
		})
	}

	// 返回可用优惠券列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取可用优惠券列表成功",
		"data":    availableCoupons,
	}
	c.ServeJSON()
}

// UseCoupon 使用优惠券
func (c *CouponController) UseCoupon() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	issueId, _ := c.GetInt64("issue_id")
	orderId, _ := c.GetInt64("order_id")
	orderNo := c.GetString("order_no")
	amount, _ := c.GetFloat("amount", 0)

	if issueId <= 0 || orderId <= 0 || orderNo == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券是否可用
	usable, message := models.CheckCouponUsable(issueId, amount)
	if !usable {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 使用优惠券
	if err := models.UseCoupon(issueId, orderId, orderNo); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "使用优惠券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "优惠券使用成功",
	}
	c.ServeJSON()
}

// GetCouponByCode 根据优惠券码获取优惠券信息
func (c *CouponController) GetCouponByCode() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券码
	code := c.GetString("code")
	if code == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券码不能为空",
		}
		c.ServeJSON()
		return
	}

	// 查询优惠券发放记录
	issue, err := models.GetCouponIssueByCode(code)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券码",
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券状态
	if issue.Status != 0 {
		var statusMsg string
		switch issue.Status {
		case 1:
			statusMsg = "已使用"
		case 2:
			statusMsg = "已过期"
		case 3:
			statusMsg = "已作废"
		default:
			statusMsg = "无效"
		}

		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该优惠券" + statusMsg,
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券归属
	if issue.MemberId != 0 && issue.MemberId != member.Id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该优惠券不属于您",
		}
		c.ServeJSON()
		return
	}

	// 检查有效期
	now := time.Now().Unix()
	if now < issue.ValidFrom {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该优惠券未到使用时间",
		}
		c.ServeJSON()
		return
	}

	if now > issue.ValidUntil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该优惠券已过期",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券详情
	coupon, err := models.GetCouponById(issue.CouponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券信息失败",
		}
		c.ServeJSON()
		return
	}

	// 如果是未领取的优惠券，则自动分配给当前用户
	if issue.MemberId == 0 {
		issue.MemberId = member.Id
		issue.UpdatedAt = now
		models.UpdateCouponIssue(issue)
	}

	// 返回优惠券信息
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券信息成功",
		"data": map[string]interface{}{
			"id":          issue.Id,
			"coupon_id":   coupon.Id,
			"name":        coupon.Name,
			"type":        coupon.Type,
			"value":       coupon.Value / 100,
			"min_consume": coupon.MinConsume / 100,
			"status":      issue.Status,
			"valid_from":  issue.ValidFrom,
			"valid_until": issue.ValidUntil,
			"start_time":  coupon.StartTime,
			"end_time":    coupon.EndTime,
			"description": coupon.Description,
			"use_rules":   coupon.UseRules,
			"code":        issue.Code,
		},
	}
	c.ServeJSON()
}

// VerifyCoupon 验证优惠券
func (c *CouponController) VerifyCoupon() {
	// 获取当前用户信息（店员或管理员）
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取请求参数
	var req struct {
		Code    string `json:"code"`
		StoreId int64  `json:"store_id"`
		Type    string `json:"type"` // 券类型：meituan/douyin/normal
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
		}
		c.ServeJSON()
		return
	}

	// 验证参数
	if req.Code == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券码不能为空",
		}
		c.ServeJSON()
		return
	}

	if req.StoreId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(req.StoreId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "找不到该门店信息",
		}
		c.ServeJSON()
		return
	}

	// 根据券类型处理不同的验券逻辑
	switch req.Type {
	case "meituan":
		// 处理美团券
		order, err := models.GetMeituanGroupOrderByCode(req.Code)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无效的美团券码",
			}
			c.ServeJSON()
			return
		}

		// 检查券是否已使用
		if order.IsUsed == 1 {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "该美团券已使用",
			}
			c.ServeJSON()
			return
		}

		// 调用美团API使用券
		meituanService, err := services.GetMeituanServiceByStoreId(order.StoreId)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "加载美团配置失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		err = meituanService.UseVoucher(order.OrderId, order.VoucherCode)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "美团券核销失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		// 更新订单状态
		err = models.UseMeituanGroupOrder(order.Id)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "更新美团券状态失败",
			}
			c.ServeJSON()
			return
		}

		// 创建团购订单
		groupBuyOrder := &models.GroupBuyOrder{
			OrderNo:      order.OrderId,
			Type:         "meituan",
			ActivityId:   0, // 美团券没有关联的活动
			ActivityName: "美团券",
			MemberId:     0, // 核销时可能没有会员信息
			Quantity:     1,
			Amount:       int64(order.TotalPrice),
			Status:       models.OrderStatusCompleted,
			GroupStatus:  models.GroupStatusSuccess,
			PaidAt:       time.Now().Unix(),
		}
		models.CreateGroupBuyOrder(groupBuyOrder)

		// 创建验券记录
		verify := &models.GroupBuyVerify{
			GroupBuyActivityId: 0,
			GroupBuyOrderId:    0,
			MemberId:           0,
			OrderId:            order.Id,
			OrderNo:            order.OrderId,
			StoreId:            store.Id,
			OperatorId:         member.Id,
			OrderAmount:        float64(order.TotalPrice) / 100,
			VerifyTime:         time.Now().Unix(),
			Remark:             fmt.Sprintf("美团券核销[订单号:%s]", order.OrderId),
		}
		models.CreateGroupBuyVerify(verify)

		c.Data["json"] = map[string]interface{}{
			"success": true,
			"message": "美团券核销成功",
			"data": map[string]interface{}{
				"order_id":      order.OrderId,
				"total_price":   order.TotalPrice / 100,
				"verify_time":   time.Now().Format("2006-01-02 15:04:05"),
				"store_name":    store.Name,
				"operator_name": member.Name,
			},
		}
		c.ServeJSON()
		return

	case "douyin":
		// 处理抖音券
		order, err := models.GetDouyinGroupOrderByCode(req.Code)
		if err != nil || order == nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无效的抖音券码",
			}
			c.ServeJSON()
			return
		}

		// 检查券是否已使用
		if order.IsUsed == 1 {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "该抖音券已使用",
			}
			c.ServeJSON()
			return
		}

		// 调用抖音API使用券
		douyinService := services.NewDouyinAPIService()
		err = douyinService.LoadConfig(store.Id)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "加载抖音配置失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		err = douyinService.UseVoucher(order.OrderId, order.VoucherCode)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "抖音券核销失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		// 更新订单状态
		err = models.UseDouyinGroupOrder(order.Id)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "更新抖音券状态失败",
			}
			c.ServeJSON()
			return
		}

		// 创建团购订单
		groupBuyOrder := &models.GroupBuyOrder{
			OrderNo:      order.OrderId,
			Type:         "douyin",
			ActivityId:   0, // 抖音券没有关联的活动
			ActivityName: "抖音券",
			MemberId:     0, // 核销时可能没有会员信息
			Quantity:     1,
			Amount:       int64(order.TotalPrice),
			Status:       models.OrderStatusCompleted,
			GroupStatus:  models.GroupStatusSuccess,
			PaidAt:       time.Now().Unix(),
		}
		models.CreateGroupBuyOrder(groupBuyOrder)

		// 创建验券记录
		verify := &models.GroupBuyVerify{
			GroupBuyActivityId: 0,
			GroupBuyOrderId:    0,
			MemberId:           0,
			OrderId:            order.Id,
			OrderNo:            order.OrderId,
			StoreId:            store.Id,
			OperatorId:         member.Id,
			OrderAmount:        float64(order.TotalPrice),
			VerifyTime:         time.Now().Unix(),
			Remark:             fmt.Sprintf("抖音券核销[订单号:%s]", order.OrderId),
		}
		models.CreateGroupBuyVerify(verify)

		c.Data["json"] = map[string]interface{}{
			"success": true,
			"message": "抖音券核销成功",
			"data": map[string]interface{}{
				"order_id":      order.OrderId,
				"pay_amount":    order.TotalPrice,
				"verify_time":   time.Now().Format("2006-01-02 15:04:05"),
				"store_name":    store.Name,
				"operator_name": member.Name,
			},
		}
		c.ServeJSON()
		return

	default:
		// 处理普通优惠券
		// 查询优惠券发放记录
		issue, err := models.GetCouponIssueByCode(req.Code)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无效的优惠券码",
			}
			c.ServeJSON()
			return
		}

		// 检查优惠券状态
		if issue.Status != 0 {
			var statusMsg string
			switch issue.Status {
			case 1:
				statusMsg = "已使用"
			case 2:
				statusMsg = "已过期"
			case 3:
				statusMsg = "已作废"
			default:
				statusMsg = "无效"
			}

			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "该优惠券" + statusMsg,
			}
			c.ServeJSON()
			return
		}

		// 检查有效期
		now := time.Now().Unix()
		if now < issue.ValidFrom {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "该优惠券未到使用时间",
			}
			c.ServeJSON()
			return
		}

		if now > issue.ValidUntil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "该优惠券已过期",
			}
			c.ServeJSON()
			return
		}

		// 获取优惠券详情
		coupon, err := models.GetCouponById(issue.CouponId)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "获取优惠券信息失败",
			}
			c.ServeJSON()
			return
		}

		// 获取会员信息（如果有）
		var memberInfo *models.Member
		if issue.MemberId > 0 {
			memberInfo, _ = models.GetMemberById(issue.MemberId, member.FranchiseId)
		}

		// 更新优惠券发放记录状态
		issue.Status = 1 // 已使用
		issue.UsedTime = now
		if err := models.UpdateCouponIssue(issue); err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "更新优惠券状态失败: " + err.Error(),
			}
			c.ServeJSON()
			return
		}

		// 准备响应数据
		responseData := map[string]interface{}{
			"coupon_id":    coupon.Id,
			"coupon_name":  coupon.Name,
			"coupon_type":  coupon.Type,
			"coupon_value": coupon.Value,
			"code":         issue.Code,
			"store_id":     store.Id,
			"store_name":   store.Name,
			"verify_time":  time.Now().Format("2006-01-02 15:04:05"),
		}

		// 添加会员信息
		if memberInfo != nil {
			responseData["member_id"] = memberInfo.Id
			responseData["member_name"] = memberInfo.Name
			responseData["member_phone"] = memberInfo.Phone
		}

		c.Data["json"] = map[string]interface{}{
			"success": true,
			"message": "优惠券核销成功",
			"data":    responseData,
		}
		c.ServeJSON()
		return
	}
}

// GetUsageRange 获取优惠券使用范围
func (c *CouponController) GetUsageRange() {
	couponId, _ := strconv.ParseInt(c.GetString("id"), 10, 64)
	if couponId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券ID",
		}
		c.ServeJSON()
		return
	}

	coupon, err := models.GetCouponById(couponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "找不到该优惠券",
		}
		c.ServeJSON()
		return
	}

	var stores []models.Store
	var venues []models.Venue
	o := orm.NewOrm()

	if coupon.ApplicableType == 1 { // 指定门店
		var storeIds []int
		if err := json.Unmarshal([]byte(coupon.ApplicableIds), &storeIds); err == nil && len(storeIds) > 0 {
			_, _ = o.QueryTable(new(models.Store)).Filter("id__in", storeIds).All(&stores, "Id", "Name")
		}
	} else if coupon.ApplicableType == 2 { // 指定场地
		var venueIds []int
		if err := json.Unmarshal([]byte(coupon.ApplicableIds), &venueIds); err == nil && len(venueIds) > 0 {
			_, _ = o.QueryTable(new(models.Venue)).Filter("id__in", venueIds).All(&venues, "Id", "Name")
		}
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"stores": stores,
			"venues": venues,
		},
	}
	c.ServeJSON()
}

// GetExchangeableCoupons 获取可兑换的优惠券列表
func (c *CouponController) GetExchangeableCoupons() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取会员等级和积分
	memberInfo, err := models.GetMemberById(member.Id, member.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员信息失败",
		}
		c.ServeJSON()
		return
	}

	// 获取有效的优惠券列表
	coupons, err := models.GetValidCoupons()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 筛选可兑换的优惠券
	var exchangeableCoupons []map[string]interface{}
	now := time.Now().Unix()

	for _, coupon := range coupons {
		// 检查优惠券是否在有效期内
		if now < coupon.StartTime || now > coupon.EndTime {
			logs.Debug("检查优惠券是否在有效期内")
			continue
		}

		// 检查优惠券是否已达到发放上限
		if coupon.TotalCount > 0 && coupon.IssuedCount >= coupon.TotalCount {
			logs.Debug("检查优惠券是否已达到发放上限")
			continue
		}

		// 检查会员是否已领取超过限制
		available, _ := models.CheckCouponAvailable(coupon.Id, member.Id)
		if !available {
			logs.Debug("检查会员是否已领取超过限制")
			continue
		}

		// 根据会员等级筛选可兑换的优惠券
		// 这里可以添加会员等级的限制逻辑

		// 设置兑换所需积分，这里使用简单规则：优惠券价值 * 10
		requiredPoints := int(coupon.Value / 1000) // 将分转换为元后乘以10
		if requiredPoints < 100 {
			requiredPoints = 100 // 最低100积分
		}

		exchangeableCoupons = append(exchangeableCoupons, map[string]interface{}{
			"id":              coupon.Id,
			"name":            coupon.Name,
			"type":            coupon.Type,
			"value":           coupon.Value / 100,      // 转换为元
			"min_consume":     coupon.MinConsume / 100, // 转换为元
			"description":     coupon.Description,
			"use_rules":       coupon.UseRules,
			"required_points": requiredPoints,
			"valid_days":      coupon.ValidDays,
			"condition":       fmt.Sprintf("订单金额满%.2f元可用", coupon.MinConsume/100),
			"status":          coupon.Status,
			"start_time":      coupon.StartTime,
			"end_time":        coupon.EndTime,
		})
	}

	// 返回可兑换优惠券列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取可兑换优惠券列表成功",
		"data": map[string]interface{}{
			"list":          exchangeableCoupons,
			"member_points": memberInfo.Points,
		},
	}
	c.ServeJSON()
}

// ExchangeCoupon 兑换优惠券
func (c *CouponController) ExchangeCoupon() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req struct {
		CouponId int64 `json:"coupon_id"`
	}
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil || req.CouponId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数错误",
		}
		c.ServeJSON()
		return
	}

	couponId := req.CouponId

	// 获取优惠券信息
	coupon, err := models.GetCouponById(couponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券不存在",
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券是否可领取
	available, message := models.CheckCouponAvailable(couponId, member.Id)
	if !available {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 计算所需积分
	requiredPoints := int(coupon.Value / 1000) // 将分转换为元后乘以10
	if requiredPoints < 100 {
		requiredPoints = 100 // 最低100积分
	}

	// 获取会员信息
	memberInfo, err := models.GetMemberById(member.Id, member.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员信息失败",
		}
		c.ServeJSON()
		return
	}

	// 检查积分是否足够
	if memberInfo.Points < requiredPoints {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "积分不足",
		}
		c.ServeJSON()
		return
	}

	// 开始事务
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}

	// 生成优惠券码
	code := fmt.Sprintf("EC%s%d", time.Now().Format("20060102"), couponId)

	// 计算有效期
	now := time.Now().Unix()
	validFrom := now
	validUntil := now + int64(coupon.ValidDays*86400)

	// 创建优惠券发放记录
	issue := &models.CouponIssue{
		MemberId:   member.Id,
		CouponId:   couponId,
		ActivityId: 0, // 0表示手动兑换
		Code:       code,
		Status:     0, // 未使用
		ValidFrom:  validFrom,
		ValidUntil: validUntil,
	}
	issue.BeforeInsert()
	// 插入发放记录
	issueId, err := o.Insert(issue)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建优惠券记录失败",
		}
		c.ServeJSON()
		return
	}

	// 增加优惠券已发放数量
	_, err = o.QueryTable(new(models.Coupon)).Filter("id", couponId).Update(orm.Params{
		"issued_count": orm.ColValue(orm.ColAdd, 1),
		"updated_at":   now,
	})
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新优惠券数量失败",
		}
		c.ServeJSON()
		return
	}

	// 扣减会员积分
	_, err = o.QueryTable(new(models.Member)).Filter("id", member.Id).Update(orm.Params{
		"points":     orm.ColValue(orm.ColMinus, requiredPoints),
		"updated_at": now,
	})
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "扣减积分失败",
		}
		c.ServeJSON()
		return
	}

	// 添加积分变动记录
	pointRecord := &models.PointsLog{
		MemberId:     member.Id,
		Points:       -requiredPoints,
		Type:         5, // 5:积分兑换
		OrderNo:      "",
		Description:  fmt.Sprintf("兑换优惠券: %s", coupon.Name),
		Operator:     "",
		BeforePoints: memberInfo.Points,
		AfterPoints:  memberInfo.Points - requiredPoints,
	}
	pointRecord.BeforeInsert()
	_, err = o.Insert(pointRecord)
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "记录积分变动失败",
		}
		c.ServeJSON()
		return
	}

	// 提交事务
	err = tx.Commit()
	if err != nil {
		tx.Rollback()
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "兑换成功",
		"data": map[string]interface{}{
			"coupon_id":     couponId,
			"issue_id":      issueId,
			"code":          code,
			"valid_from":    validFrom,
			"valid_until":   validUntil,
			"points_used":   requiredPoints,
			"points_remain": memberInfo.Points - requiredPoints,
		},
	}
	c.ServeJSON()
}
